<template>
  <div class="search-container">
    <div class="search-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索菜品名称..."
        class="search-input"
        @keyup.enter.native="handleSearch"
        clearable
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <div class="search-results" v-loading="loading">
      <el-row :gutter="20">
        <el-col 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6" 
          v-for="dish in dishes" 
          :key="dish.dishid"
        >
          <el-card class="dish-card" shadow="hover">
            <div class="dish-image">
              <img :src="dish.dishcover || require('@/assets/dishes/dish1.jpg')" :alt="dish.dishname">
            </div>
            <div class="dish-info">
              <h3 class="dish-name">{{ dish.dishname }}</h3>
              <p class="dish-description">{{ dish.dishdescribe || '暂无描述' }}</p>
              <div class="dish-price">¥{{ dish.dishprice }}</div>
              <div class="dish-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewStore(dish.storeid)"
                >
                  查看商店
                </el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  @click="addToCart(dish)"
                  v-if="isLoggedIn"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <div class="no-results" v-if="!loading && dishes.length === 0">
        <el-empty description="暂无搜索结果"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import { searchDishes } from '@/api/dish'
import { addToCart } from '@/api/cart'
import { mapGetters } from 'vuex'

export default {
  name: 'Search',
  data() {
    return {
      searchKeyword: '',
      dishes: [],
      loading: false,
      currentPage: 1,
      pageSize: 12,
      total: 0
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'userInfo'])
  },
  methods: {
    async handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键词')
        return
      }
      
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword.trim()
        }
        
        const response = await searchDishes(params)
        const data = response.data.data
        
        this.dishes = data.list || []
        this.total = data.total || 0
      } catch (error) {
        this.$message.error('搜索失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.handleSearch()
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.handleSearch()
    },
    
    viewStore(storeId) {
      this.$router.push(`/store/detail/${storeId}`)
    },
    
    async addToCart(dish) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      try {
        await addToCart(dish.dishname, dish.dishprice, this.userInfo.userid)
        this.$message.success('已添加到购物车')
      } catch (error) {
        this.$message.error('添加失败：' + error.message)
      }
    }
  },
  
  mounted() {
    // 从路由参数获取搜索关键词
    const keyword = this.$route.query.keyword
    if (keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  padding: 20px;
  
  .search-header {
    margin-bottom: 30px;
    text-align: center;
    
    .search-input {
      max-width: 500px;
    }
  }
  
  .search-results {
    .dish-card {
      margin-bottom: 20px;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .dish-image {
        height: 200px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .dish-info {
        padding: 15px 0;
        
        .dish-name {
          margin: 0 0 10px 0;
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }
        
        .dish-description {
          margin: 0 0 10px 0;
          color: #666;
          font-size: 14px;
          line-height: 1.4;
          height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .dish-price {
          font-size: 18px;
          font-weight: bold;
          color: #e74c3c;
          margin-bottom: 15px;
        }
        
        .dish-actions {
          display: flex;
          gap: 10px;
          
          .el-button {
            flex: 1;
          }
        }
      }
    }
  }
  
  .pagination-container {
    text-align: center;
    margin-top: 30px;
  }
  
  .no-results {
    text-align: center;
    margin-top: 50px;
  }
}
</style> 